package com.hyy.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.concurrent.Callable;


/*
* 用于序列化*/
public class JacksonUtil {

    private final static ObjectMapper OBJECT_MAPPER;
    static {
        OBJECT_MAPPER=new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }


    //这里借鉴spring的写法，对异常进行捕获在 Extension中spring框架中->org.springframework.boot.json.JacksonJsonParser
    private static  <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }
    //这里借鉴spring的写法，对异常进行捕获，让代码更优雅
    private static  <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            //判断var4是否是check以及其子类
            if (check.isAssignableFrom(var4.getClass())) {
                try {
                    throw new JsonParseException(var4.getMessage());//这里参数需要传递字符串
                } catch (JsonParseException e) {
                    throw new RuntimeException(e);
                }
            }

            throw new IllegalStateException(var4);
        }
    }

    //序列化
    public static String writeValueAsString(Object value) {
        return JacksonUtil.tryParse(() -> OBJECT_MAPPER.writeValueAsString(value));
    }

    //反序列化
    public static <T> T readValue(String content,Class<T> valueType){
        return JacksonUtil.tryParse(() -> OBJECT_MAPPER.readValue(content, valueType));
    }

    //List的反序列化
    public static <T> T readValueAndList(String content,Class<?> paramClasses){
        JavaType javaType=OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, paramClasses);
        return  JacksonUtil.tryParse(() -> OBJECT_MAPPER.readValue(content, javaType));
    }



}
